package dnl.jexem.remote;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.lang.math.RandomUtils;
import org.jasypt.util.text.BasicTextEncryptor;

/**
 * A central registry of passwords. Each time a password is required, it is read
 * from a file and then decrypted. Passwords have internal ids. The 'real'
 * passwords may be retrieved only by their ids.
 * 
 * @author Daniel Orr
 */
public class PasswordRegistry {
	//private static final Logger logger = LoggerFactory.getLogger(PasswordRegistry.class);
	private static final String ENCRYPTOR_PASSWORD = "d5a4n3i2e1l";
	private BasicTextEncryptor encryptor;

	public PasswordRegistry() {
		encryptor = new BasicTextEncryptor();
		encryptor.setPassword(ENCRYPTOR_PASSWORD);
	}

	/**
	 * Saves the given password to the passwords registry file.
	 * 
	 * @param password
	 *            a password to save.
	 * @return the password id.
	 * @throws EncryptionException
	 * @throws IOException
	 */
	public synchronized String savePassword(String password) throws IOException {
		String id = null;
		String encrypted = encryptor.encrypt(password);
		Properties p = loadPasswordFromFile();
		while (id == null || p.containsKey(id)) {
			id = "pass" + RandomUtils.nextInt();
		}
		p.put(id, encrypted);
		savePasswordFile(p);
		return id;
	}

	/**
	 * Gets the password of the corresponding id.
	 * 
	 * @param id
	 *            a password's id.
	 * @return the original, decrypted, password.
	 * @throws DecryptionException
	 * @throws IOException
	 */
	public synchronized String getPassword(String id) throws IOException {
		Properties p = loadPasswordFromFile();
		String pass = (String) p.get(id);
		return encryptor.decrypt(pass);
	}

	private Properties loadPasswordFromFile() throws IOException {
		Properties props = new Properties();
		File propsFile = new File("passw");
		if (propsFile.exists()) {
			props.load(new FileInputStream(propsFile));
		} else {
			//LightLog.error("Passwords file not found.");
		}
		return props;
	}

	private void savePasswordFile(Properties props) throws IOException {
		File propsFile = new File("passw");
		props.store(new FileOutputStream(propsFile), "");
	}

	public static void main(String[] args) throws IOException {
		new PasswordRegistry().savePassword("hereiam");
	}
}
